package util.encrypt;

import java.security.MessageDigest;
import java.util.Random;

/**
 * 产生随机数的种子藏在密文的最后一ch
 * @author Administrator
 *
 */
public class Encrypter {
	public static String getEncryptedStr(String data) {
		if(null==data || "".equals(data)){
			return data;
		}
		try {
			byte[] bytes = data.getBytes("UTF-8");
			char[] chars = new char[bytes.length+1];
			int num = bytes.length;
			byte key = 0;
			char seed = (char)(new Random(System.currentTimeMillis()).nextInt()%Byte.MAX_VALUE + Byte.MAX_VALUE);//seed范围在0~255之间随机,和密文保持一致
			Random r = new Random(seed);
			for (int i = 0; i < num; i++) {
				key = (byte)r.nextInt();
				//chars[i]范围在0~255之间
				chars[i] = (char) ((byte)(bytes[i] ^ key) + 128);
			}
			chars[bytes.length] = seed;
			return new String(chars);
		} catch (Exception e) {
			return null;
		}
	}

	public static String getDecryptedStr(String data) {
		try {
			char[] chars = data.toCharArray();
			int num = chars.length-1;
			byte[] bytes = new byte[num];
			char seed = chars[num];
			byte key = 0;
			Random r = new Random(seed);
			for (int i = 0; i < num; i++) {
				key = (byte)r.nextInt();
				bytes[i] = (byte) ((chars[i] - 128) ^ (key));
			}
			return new String(bytes, "UTF-8");
		} catch (Exception e) {
			return null;
		}
	}
	
	/**
	 * @param data 注意，需要统一String的编码格式，此方法编码格式选择的是"utf-8";还需注意16位大消息，顺序及字符
	 * @return
	 */
	public static String getMd5Str(String data){
		char hexDigits[]={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'}; 
		try {
			byte[] btInput = data.getBytes("utf-8");
			// 获得MD5摘要算法的 MessageDigest 对象
			MessageDigest mdInst = MessageDigest.getInstance("MD5");
			// 使用指定的字节更新摘要
			mdInst.update(btInput);
			// 获得密文
			byte[] md = mdInst.digest();
			// 把密文转换成十六进制的字符串形式
			int j = md.length;
			char str[] = new char[j * 2];
			int k = 0;
			for (int i = 0; i < j; i++) {
				byte byte0 = md[i];
				str[k++] = hexDigits[byte0 >>> 4 & 0xf];
				str[k++] = hexDigits[byte0 & 0xf];
			}
			return new String(str);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

}
